import { useEffect, useState } from 'react';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import IconButton from '@mui/material/IconButton';
import DeleteIcon from '@mui/icons-material/Delete'
import EditIcon from '@mui/icons-material/Edit'
import Fab from '@mui/material/Fab';
import AddIcon from '@mui/icons-material/Add';
import { useNavigate } from 'react-router-dom';
import { ConfirmDialog } from './../../components'
import { roomService } from "../../services";
import { useMessage } from '../../hooks';
import { Button } from '@mui/material';

const columns = [
  { id: 'id', label: 'Room Id', minWidth: 30 },
  { id: 'name', label: 'Name', minWidth: 170 },
  { id: 'capacity', label: 'Capacity', minWidth: 100 },
  { id: 'description', label: 'Description', minWidth: 40 },
  // { id: 'createDate', label: 'Create Date', minWidth: 170 },
  // { id: 'lastUpdateDate', label: 'Last Update Date', minWidth: 170 },
  { id: 'action', label: 'Action', minWidth: 30 },
];

export default function Rooms() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [pageNumber, setPageNumber] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [open, setOpen] = useState(false);
  const [roomId, setRoomId] = useState(0);
  const { showError, showSuccess } = useMessage();
  const [isRefresh, setIsRefresh] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await roomService.getRooms(pageNumber, pageSize);
        setData(response);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [pageNumber, pageSize, isRefresh]);

  const onChangePageNumber = (event, newNumber) => {
    setPageNumber(newNumber);
  };

  const onChangePageSize = (event) => {
    setPageSize(+event.target.value);
    setPageNumber(0);
  };

  const onCreateRoom = () => {
    navigate("/room-create");
  }
  const onEditRoom = (roomId, name, capacity, description) => {
    navigate(`/room-edit/${roomId}/${name}/${capacity}/${description}`);
  }

  const onDeleteRoom = (roomId) => {
    setRoomId(roomId);
    setOpen(true);
  }

  const onYes = async () => {
    setOpen(false);
    try {
      await roomService.delete(roomId).then(result => {
        showSuccess('deleted room successfully');
        setIsRefresh(true);
      })
    } catch (err) {
      showError(err);
    } finally {
      setLoading(false);
    }
  }

  const onNo = () => setOpen(false);

  if (loading) return <div>Loading...</div>;
  if (error) return <div style={{ color: 'red' }}>{error}</div>;

  return (
    <> 
      <Paper sx={{ width: '100%', overflow: 'hidden' }}>
        <TableContainer sx={{ maxHeight: '80vh' }}>
          <Table stickyHeader aria-label="sticky table">
            <TableHead>
              <TableRow>
                {columns.map((column) => (
                  <TableCell
                    key={column.id}
                    align={column.align}
                    style={{ minWidth: column.minWidth }}>
                    {column.label}
                    {column.id === 'action' ? 
                    (<Button color="primary" aria-label="add">
                      <AddIcon onClick={onCreateRoom} align='right' />
                    </Button>)
                    : null}
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {data?.items.map((row) => {
                return (
                  <TableRow hover role="checkbox" tabIndex={-1} key={row.id}>
                    {columns.map((column) => {
                      const value = row[column.id];
                      return (
                        <TableCell key={column.id} align={column.align}>
                          {column.id === 'action' ?
                            <div>
                              <IconButton aria-label="edit" onClick={() => onEditRoom(row.id, row.name, row.capacity, row.description)}>
                                <EditIcon color='success' />
                              </IconButton>
                              <IconButton color='warning' aria-label="delete" onClick={() => onDeleteRoom(row.id)}>
                                <DeleteIcon />
                              </IconButton>
                            </div> :
                            value
                          }
                        </TableCell>
                      );
                    })}
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[10, 25, 100]}
          component="div"
          count={data?.totalCount}
          rowsPerPage={pageSize}
          page={pageNumber}
          onPageChange={onChangePageNumber}
          onRowsPerPageChange={onChangePageSize}
        />
      </Paper>
      <ConfirmDialog message={'Are you sure you want to delete this room?'} open={open} onYes={onYes} onNo={onNo} />
    </>
  );
}
